package com.njtoyo.taxi.admin.service.marketing.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njtoyo.taxi.admin.library.Const;
import com.njtoyo.taxi.admin.library.common.OperationRecordHelper;
import com.njtoyo.taxi.admin.library.common.util.CopyUtil;
import com.njtoyo.taxi.admin.mapper.master.entity.CouponTemplate;
import com.njtoyo.taxi.admin.mapper.master.enums.CouponCategory;
import com.njtoyo.taxi.admin.mapper.master.enums.CouponSourceChannel;
import com.njtoyo.taxi.admin.mapper.master.enums.CouponUsageCondition;
import com.njtoyo.taxi.admin.mapper.master.mapper.CouponTemplateMapper;
import com.njtoyo.taxi.admin.rest.presenter.marketing.CouponTemplateSimplePresenter;
import com.njtoyo.taxi.admin.rest.wrapper.marketing.couponTemplate.CouponListWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.marketing.couponTemplate.CreateCouponWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.marketing.couponTemplate.UpdateCouponWrapper;
import com.njtoyo.taxi.admin.service.marketing.CouponTemplateService;
import com.taxi.entity.common.RestResult;
import com.taxi.entity.common.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

@Component
@DS(Const.PRIMARY_DS)
public class CouponTemplateServiceImpl implements CouponTemplateService {

    @Autowired
    private CouponTemplateMapper couponTemplateMapper;
    @Autowired
    private OperationRecordHelper operationRecordHelper;

    @Override
    public RestResult<List<CouponTemplateSimplePresenter>> getAll() {
        QueryWrapper<CouponTemplate> wrapper = new QueryWrapper<>();
        wrapper.select("id", "title");
        wrapper.orderByDesc("id");
        List<CouponTemplate> list = couponTemplateMapper.selectList(wrapper);
        List<CouponTemplateSimplePresenter> res = CopyUtil.copyList(list, CouponTemplateSimplePresenter.class);
        return RestResult.success(res);
    }

    /**
     * 优惠券模板列表
     *
     * @param couponListWrapper
     * @return
     */
    @Override
    public RestResult<Page<CouponTemplate>> getList(CouponListWrapper couponListWrapper) {
        Page<CouponTemplate> couponTemplatePage =
                couponTemplateMapper.selectPage(couponListWrapper);
        return RestResult.success(couponTemplatePage);
    }

    /**
     * 增加优惠券模板
     *
     * @return
     */
    @Override
    public RestResult addCoupons(CreateCouponWrapper createCouponWrapper) {
        CouponTemplate copy = CopyUtil.copy(createCouponWrapper, CouponTemplate.class);
        //优惠券类型校验
        Integer check = new LambdaQueryChainWrapper<>(couponTemplateMapper)
                .eq(CouponTemplate::getTitle, copy.getTitle())
                .count();

        if (check > 0) {
            return RestResult.failed("优惠券模板标题已经存在");
        }
        RestResult validation = validation(copy);
        if (validation != null) {
            return RestResult.failed(validation.getMsg());
        }
        couponTemplateMapper.insert(copy);
        operationRecordHelper.addBusinessLog(String.format("新增了优惠券模板标题 [%s] 的信息",createCouponWrapper.getTitle()));
        return RestResult.success();
    }

    /**
     * 修改优惠券模板
     *
     * @return
     */
    @Override
    public RestResult updateCoupons(Long id, UpdateCouponWrapper updateCouponWrapper) {
        CouponTemplate couponTemplate = couponTemplateMapper.selectById(id);
        if (ObjectUtils.isEmpty(couponTemplate)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        CouponTemplate copy = CopyUtil.copy(updateCouponWrapper, CouponTemplate.class);
        //优惠券类型校验
        Integer check = new LambdaQueryChainWrapper<>(couponTemplateMapper)
                .eq(CouponTemplate::getTitle, copy.getTitle())
                .count();

        if (check > 0 && !updateCouponWrapper.getTitle().equals(couponTemplate.getTitle())) {
            return RestResult.failed("优惠券模板标题已经存在其他的");
        }
        RestResult validation = validation(copy);
        if (validation != null) {
            return RestResult.failed(validation.getMsg());
        }
        new LambdaUpdateChainWrapper<>(couponTemplateMapper)
                .eq(CouponTemplate::getId, id)
                .set(CouponTemplate::getTitle, updateCouponWrapper.getTitle())
                .set(CouponTemplate::getCategory, updateCouponWrapper.getCategory())
                .set(CouponTemplate::getCouponValue, updateCouponWrapper.getCouponValue())
                .set(CouponTemplate::getSpecifics, updateCouponWrapper.getSpecifics())
                .set(CouponTemplate::getScope, updateCouponWrapper.getScope())
                .set(CouponTemplate::getPlatform, updateCouponWrapper.getPlatform())
                .set(CouponTemplate::getSourceChannel, updateCouponWrapper.getSourceChannel())
                .set(CouponTemplate::getUsageCondition, updateCouponWrapper.getUsageCondition())
                .set(CouponTemplate::getUsageLimit, updateCouponWrapper.getUsageLimit())
                .set(CouponTemplate::getEffectiveAfter, updateCouponWrapper.getEffectiveAfter())
                .set(CouponTemplate::getEffectiveDuration, updateCouponWrapper.getEffectiveDuration())
                .update();
        operationRecordHelper.addBusinessLog(String.format("修改了优惠券模板 [%d] 的信息为%s",id,updateCouponWrapper.getTitle()));
        return RestResult.success();
    }

    /**
     * 验证优惠券模板
     */
    public RestResult validation(CouponTemplate couponTemplate) {
        CouponCategory category = couponTemplate.getCategory();
        String usageLimit = couponTemplate.getUsageLimit();
        CouponUsageCondition usageCondition = couponTemplate.getUsageCondition();
        BigDecimal couponValue = couponTemplate.getCouponValue();
        // 判断是否是整数或者是携带一二位的小数
        boolean flag = true;
        boolean usageLimitflag = false;
        Pattern pattern = compile("^[+]?([0-9]+(.[0-9]{1,2})?)$");
        CouponSourceChannel sourceChannel = couponTemplate.getSourceChannel();
        if (!CouponSourceChannel.activity_team.equals(sourceChannel)) {
            if (couponValue != null) {
                if (!pattern.matcher(couponValue.toString()).matches()) {
                    flag = false;
                }
            }else {
                flag = false;
            }
        }
        if (usageLimit != null) {
            if (pattern.matcher(usageLimit).matches()) {
                usageLimitflag = true;
            }
        }
        switch (category) {
            //立减
            case reduction:
                if (!flag) {
                    return RestResult.failed("优惠券类型立减优惠券面值应为金额模式");
                }
                if (usageCondition != null || usageLimit != null) {
                    return RestResult.failed("优惠券类型立减使用条件限制应为null");
                }
                break;
            //满减
            case fullreduction:
                if (!flag) {
                    return RestResult.failed("优惠券类型满减优惠券面值应为金额模式");
                }
                if (!usageCondition.equals(CouponUsageCondition.full)) {
                    return RestResult.failed("优惠券类型满减使用条件应为满减 0");
                }

                BigDecimal usageLimits = new BigDecimal(0);
                if (!StringUtils.isEmpty(usageLimit)) {
                    if (!usageLimit.trim().isEmpty()) {
                        usageLimits = new BigDecimal(usageLimit);
                    }
                }
                if (usageLimit == null &&
                        usageLimits.compareTo(couponValue) != 1) {
                    return RestResult.failed("优惠券类型满减门槛，金额需大于 优惠券面值");
                }
                break;
            //折扣
            case discount:
                //使用限制满减金额
                if (!flag) {
                    return RestResult.failed("优惠券类型折扣 优惠券面值应为折扣率");
                }
                if (couponValue.compareTo(BigDecimal.ZERO) != 1 && couponValue.compareTo(BigDecimal.TEN) != -1) {
                    return RestResult.failed("优惠券类型折扣率应在0和10之间");
                }
                if (!usageCondition.equals(CouponUsageCondition.max)) {
                    return RestResult.failed("优惠券类型折扣使用条件应为折扣 1");
                }
                if (!usageLimitflag) {
                    return RestResult.failed("优惠券类型折扣使用限制应为最高满减金额");
                }
                break;
            default:
                return RestResult.failed("优惠券类型错误");
        }
        return null;
    }
}
